import boss from './canvas/boss'
import bullet from './canvas/bullet'
import player from './canvas/player'
import steel from './canvas/steel'
import straw from './canvas/straw'
import tank from './canvas/tank'
import wall from './canvas/wall'
import water from './canvas/water'

import config from './config'
import audio from './service/audio'
import { promises } from './service/image'
import './style.scss'

const app = document.querySelector<HTMLDivElement>('#app')!
app.style.width = config.canvas.width + 'px'
app.style.height = config.canvas.height + 'px'

class APP {
  isStart: boolean = false
  state: number = -1
  interval: number = 0

  bootstrap() {
    app.addEventListener('click', async () => {
      await this.start()
      this.interval = setInterval(() => {
        // 玩家赢
        if (tank.models.length === 0) this.state = 1
        // 玩家输
        if (player.models.length === 0 || boss.models.length === 0)
          this.state = 0
        if (this.state !== -1) this.stop()
      }, 100)
    })
  }

  async start() {
    if (this.isStart) return
    this.isStart = true
    app.style.backgroundImage = 'none'
    // 播放开始音乐
    audio.start()
    // 加载所有贴图
    await Promise.all(promises)
    // 渲染草图
    straw.render()
    // 渲染砖墙
    wall.render()
    // 渲染水
    water.render()
    // 渲染钢铁墙
    steel.render()
    // 渲染坦克
    tank.render()
    // 渲染子弹
    bullet.render()
    // 渲染boss
    boss.render()
    // 玩家坦克
    player.render()
  }

  stop() {
    console.log('游戏结束')
    clearInterval(this.interval)
    tank.stop()
    bullet.stop()
    this.text()
  }

  text() {
    const el = document.createElement('canvas')
    el.width = config.canvas.width
    el.height = config.canvas.height
    const ctx = el.getContext('2d')!

    ctx.fillStyle = 'red'
    ctx.font = '80px CascadiaMono'
    ctx.textBaseline = 'middle'
    ctx.textAlign = 'center'

    const text = this.state === 1 ? '恭喜你，取得胜利 ！' : '啥也不是！！！'
    ctx.fillText(text, el.width / 2, el.height / 2)
    app.appendChild(el)
  }
}

export default new APP()
